import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { Message } from 'element-ui'

Vue.use(VueRouter)

// 路由规则
const routes = [
  // 登录
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "Login" */'@/views/login/login')
  },
  // 正常页面
  {
    path: '/',
    component: () => import(/* webpackChunkName: "Index" */'@/views/layout/layout'),
    redirect: '/user',
    meta: { requiresAuth: true },
    children: [
      // 用户管理
      {
        path: '/user',
        name: 'user',
        component: () => import(/* webpackChunkName: "Index" */'@/views/user/user')
      },
      // 书籍管理
      {
        path: '/book',
        name: 'book',
        component: () => import(/* webpackChunkName: "Index" */'@/views/book/book')
      },
      // 创建用户
      {
        path: '/user/create',
        name: 'create-user',
        component: () => import(/* webpackChunkName: "CreateUser" */'@/views/user/create')
      },
      // 编辑用户
      {
        path: '/user/:id/edit',
        name: 'edit-user',
        component: () => import(/* webpackChunkName: "EditUser" */'@/views/user/edit'),
        props: true
      },
      // 添加书籍
      {
        path: '/book/create',
        name: 'create-book',
        component: () => import(/* webpackChunkName: "CreateBook" */'@/views/book/create')
      },
      // 编辑书籍
      {
        path: '/book/:bookId/edit',
        name: 'edit-book',
        props: true,
        component: () => import(/* webpackChunkName: "EditBook" */'@/views/book/edit')
      }
    ]
  },
  // 404
  {
    path: '*',
    name: '404',
    component: () => import(/* webpackChunkName: "Error" */'@/views/error/error')
  }
]

const router = new VueRouter({
  routes
})

// 侧边栏合法路径
const legalRoutes = ['/user', '/book', '/notification']

// 路由守卫
router.beforeEach((to, from, next) => {
  // 控制侧边栏显示正确
  const curPage = getRootRoute(to.path)
  if (curPage) {
    store.commit('changeCurPage', curPage)
  }
  // 检查随意路由是否有权限
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!store.state.user.access_token && !window.localStorage.getItem('access_token')) {
      Message.error('无权访问！请先进行登录')
      next({
        name: 'login',
        // 保存意向地址，稍后登录后跳转
        query: {
          redirect: to.fullPath
        }
      })
    } else {
      next()
    }
  } else {
    next() // 确保一定要调用 next()
  }
})

// 返回根路由
function getRootRoute (path) {
  for (let i = 0; i < legalRoutes.length; i++) {
    if (path.startsWith(legalRoutes[i])) {
      return legalRoutes[i]
    }
  }
  return ''
}

export default router
